﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using Microsoft.Shell;
namespace LinkViewer
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application, ISingleInstanceApp
    {

        [DllImportAttribute("User32.dll")]
        public static extern IntPtr SetForegroundWindow(IntPtr hWnd);

        public const int Suspended_Page_ID = 20090;
        public static string MainWindowTitle { get; set; }
        public static int LastFolderOpened { get; set; }

        private jcc.Login LoginWindow = null;
        public static System.Windows.Forms.Timer idleTimer = new System.Windows.Forms.Timer();



        /// <summary>
        /// Main Entry Point
        /// </summary>
        [STAThread]
        public static void Main()
        {
            if (SingleInstance<App>.InitializeAsFirstInstance("JetNett_Link_Viewer"))
            {
                var application = new App();
                application.Run();
                // Allow single instance code to perform cleanup operations
                SingleInstance<App>.Cleanup();
            }
        }




        public App()
        {
          
           
            Version version = System.Reflection.Assembly.GetCallingAssembly().GetName().Version;
            MainWindowTitle = "Link Viewer v{0}";
            MainWindowTitle = string.Format(MainWindowTitle, version.Major.ToString() + "." + version.Minor.ToString() + "." + version.Build.ToString());


      
            idleTimer = new System.Windows.Forms.Timer();
            idleTimer.Tick += new EventHandler(idleTimer_Tick);
            idleTimer.Interval = 30 * 60 * 1000; //30 min * 60 sec  * 1000 ms
            idleTimer.Start();

       


        }
        static int pageToOpen = 0;
        static bool launchMainForm = true;
        public static MainWindow Dashboard;
        //When a person successfully logs in
        void LoginWindow_LoginSuccess(object sender, RoutedEventArgs e)
        {
            //standard open no page to open
            if (pageToOpen == 0)
            {
                Dashboard = new MainWindow();
                Dashboard.Show();
            }
            else if (pageToOpen > 0)
            {
                if (launchMainForm)
                {
                    //launch the main form and open a page
                    Dashboard = new MainWindow(pageToOpen);
                    Dashboard.Show();
                }
                else
                {
                    //just open the page - logic taken from MainWindow(int pageToOpen) constructor
                    LinkWrapper wrapper = new LinkWrapper();

                    jcc.com.dailyez.Link[] links = jcc.StandardWebService.WebService.GetLinksFromPage(jcc.StandardWebService.GetKey(), pageToOpen);

                    foreach (jcc.com.dailyez.Link link in links)
                    {
                        DirectoryLink dirLink = new DirectoryLink();
                        dirLink.Link = link;
                        wrapper.Add(dirLink);
                    }
                    WinLinkViewer win = new WinLinkViewer(wrapper);
                    win.Show();
                }
            }

            
        }

        

        public static void ResetIdleTimer()
        {
            idleTimer.Stop();
            idleTimer.Start();
        }
        
        protected override void OnStartup(StartupEventArgs e)
        {

            Application.Current.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException);
                      
            LoginWindow = new jcc.Login("Link Viewer", 1);
            LoginWindow.LoginSuccess += new RoutedEventHandler(LoginWindow_LoginSuccess);

          

            if (e.Args.Length > 2)
            {
                jcc.Login.Username = e.Args[0];
                jcc.Login.Password = e.Args[1];
                pageToOpen = Convert.ToInt32(e.Args[2]);
                
                LoginWindow.TryLogin();
                
            }
            else if (e.Args.Length == 2)
            {
               
                jcc.Login.Username = e.Args[0];
                jcc.Login.Password = e.Args[1];
           

                LoginWindow.TryLogin();
            }
            else
            {
                LoginWindow.Show();
            }
            
            base.OnStartup(e);
        }

        void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {

            if (MessageBox.Show("The Link Viewer has encountered an unhandled exception.  The execption details will follow, for debugging please record this message (Print Screen or Similar)\n\n" + 
                "Exception Message:" + e.Exception.Message + "\n\n" +
                ((e.Exception.InnerException != null) ? "Inner Exception Message:" + e.Exception.InnerException.Message : "") + "\n\nStack Trace (important):" + e.Exception.StackTrace + "\n\nWould you like to try continuing execution anyway? (High probability the application will fail)", "Unhandled Exception", MessageBoxButton.YesNo, MessageBoxImage.Error) == MessageBoxResult.Yes)
                e.Handled = true;
        }
        void idleTimer_Tick(object sender, EventArgs e)
        {
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, 0, 0, 0, "{Username} was kicked out by the idle timer");
            Application.Current.Shutdown();
        }



        /// <summary>
        /// When we changed this to a single instance app, we can no longer restart, so this kinda fakes it
        /// </summary>
        public static void EmulateRestart()
        {
            //act as if the initialization has just completed
            Dashboard.OnReadyWorkerRunWorkerCompleted(null, null);
        }


        #region ISingleInstanceApp Members

        public bool SignalExternalCommandLineArgs(IList<string> args)
        {

            // the 0 arg is the path

            jcc.Login.Username = args[1];
            jcc.Login.Password = args[2];

            launchMainForm = false;
            pageToOpen = Convert.ToInt32(args[3]);
           // MessageBox.Show(jcc.Login.Username + " " + jcc.Login.Password + " " + pageToOpen);
            LoginWindow.TryLogin();
            


            return true;
        }

        #endregion
    }
}
